package com.tourism.admin.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tourism.admin.common.Result;
import com.tourism.admin.model.entity.User;
import com.tourism.admin.model.entity.UserRole;
import com.tourism.admin.service.RoleService;
import com.tourism.admin.service.UserRoleService;
import com.tourism.admin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleService roleService;


    @PostMapping("/login")

    public Result<?> login(@RequestBody User user) {
        return userService.login(user);
    }


    @PostMapping("/register")
    public Result<?> register(@RequestBody User user) {
        return userService.register(user);
    }


    @PostMapping("/add")
    public Result<?> saves(@RequestBody User user) {
        return userService.saves(user);
    }

    @PutMapping("/update")
    public Result<?> update(@RequestBody User user) {
        return Result.success().setData(userService.updateById(user));
    }



    @PutMapping("/pass")
    public Result<?> pass(@RequestBody Map<String, Object> map) {
        return userService.pass(map);
    }


    // 改变权限接口
    @PutMapping("/changeRole")
    public Result<?> changeRole(@RequestBody User user) {
        return userService.changeRole(user);
    }


    @DeleteMapping("delete/{id}")
    public Result<?> delete(@PathVariable Long id) {
        userRoleService.deleteByUserRoleId(id);
        return Result.success().setData(userService.removeById(id));
    }

    @GetMapping("/query/{id}")
    public Result<?> getById(@PathVariable Long id) {
        return Result.success().setData(userService.getById(id));
    }

    @GetMapping("query/all")
    public Result<?> findAll() {
        return Result.success().setData(userService.list(null));
    }

    /**
     * 统计数据
     *
     * @return
     */
    @GetMapping("/count")
    public Result<?> count() {
//        User user = getUser(); // 当前登录的用户信息
        return Result.success().setData(userService.countAddress());
    }

    /**
     * 用户分页列表查询，包含书籍表的一对多查询
     *
     * @param pageNum
     * @param pageSize
     * @param search
     * @return
     */
    @GetMapping("/page")
    public Result<?> findPage(@RequestParam(defaultValue = "1L") Integer pageNum,
                              @RequestParam(defaultValue = "100L") Integer pageSize,
                              @RequestParam(defaultValue = "") String search) {
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery().orderByAsc(User::getId);
        if (StrUtil.isNotBlank(search)) {
            wrapper.like(User::getNickName, search);
        }

        Page<User> userPage = userService.findPage(new Page<>(pageNum, pageSize), search);
        // 设置用户的角色id列表
        for (User record : userPage.getRecords()) {
            List<UserRole> roles = roleService.getUserRoleByUserId(record.getId());
            List<Integer> roleIds = roles.stream().map(UserRole::getRoleId).distinct().collect(Collectors.toList());
            record.setRoles(roleIds);
        }
        return Result.success().setData(userPage);
    }

    /**
     * Excel导出
     *
     * @param response
     * @throws IOException
     */
//    @GetMapping("/export")
//    public void export(HttpServletResponse response) throws IOException {
//
//        List<Map<String, Object>> list = CollUtil.newArrayList();
//
//        List<User> all = userMapper.selectList(null);
//        for (User user : all) {
//            Map<String, Object> row1 = new LinkedHashMap<>();
//            row1.put("用户名", user.getUsername());
//            row1.put("昵称", user.getNickName());
//            row1.put("年龄", user.getAge());
//            row1.put("性别", user.getSex());
//            row1.put("地址", user.getAddress());
//            list.add(row1);
//        }

        // 2. 写excel
//        ExcelWriter writer = ExcelUtil.getWriter(true);
//        writer.write(list, true);
//
//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
//        String fileName = URLEncoder.encode("用户信息", "UTF-8");
//        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
//
//        ServletOutputStream out = response.getOutputStream();
//        writer.flush(out, true);
//        writer.close();
//        IoUtil.close(System.out);
//    }

    /**
     * Excel导入
     * 导入的模板可以使用 Excel导出的文件
     *
     * @param file Excel
     * @return
     * @throws IOException
     */
//    @PostMapping("/import")
//    public Result<?> upload(MultipartFile file) throws IOException {
//        InputStream inputStream = file.getInputStream();
//        List<List<Object>> lists = ExcelUtil.getReader(inputStream).read(1);
//        List<User> saveList = new ArrayList<>();
//        for (List<Object> row : lists) {
//            User user = new User();
//            user.setUsername(row.get(0).toString());
//            user.setNickName(row.get(1).toString());
//            user.setAge(Integer.valueOf(row.get(2).toString()));
//            user.setSex(row.get(3).toString());
//            user.setAddress(row.get(4).toString());
//            saveList.add(user);
//        }
//        for (User user : saveList) {
//            userMapper.insert(user);
//        }
//        return Result.success();
//    }

}
